package expression;

import java.util.ArrayList;

import memory.Memory;
import exceptions.ParseException;

public class Sum extends Expression {

	ArrayList<Multiply> summands;
	ArrayList<Boolean> operations;

	public Sum(String exp, Memory memory) throws ParseException {
		super(memory);
		exp = fixString(exp);
		if (exp.length() == 0) {
			throw new ParseException("empty expression");
		}
		operations = new ArrayList<Boolean>();
		summands = new ArrayList<Multiply>();
		if (exp.charAt(0) == '-') {
			operations.add(false);
			if (exp.length() == 1) {
				throw new ParseException(exp + " is not valid expression");
			}
			exp = exp.substring(1);
		} else {
			operations.add(true);
		}
		int cnt = 0;
		int last = 0;
		int n = exp.length();
		for (int i = 0; i < n; i++) {
			if (exp.charAt(i) == '(') {
				cnt++;
			}
			if (exp.charAt(i) == ')') {
				cnt--;
			}
			if (cnt != 0) {
				continue;
			}
			if (exp.charAt(i) == '+' || exp.charAt(i) == '-') {
				if (exp.charAt(i) == '+')
					operations.add(true);
				else
					operations.add(false);
				if (i == exp.length() - 1) {
					throw new ParseException(exp + " is not valid expression");
				}
				summands.add(new Multiply(exp.substring(last, i), memory));
				last = i + 1;
			}
		}
		summands.add(new Multiply(exp.substring(last, n), memory));
	}

	private String fixString(String s) {
		s = s.replaceAll(" ", "");
		s = s.replaceAll("\t", "");
		return s;
	}

	@Override
	public int calculate() {
		int x = 0;
		for (int i = 0; i < summands.size(); i++) {
			if (operations.get(i)) {
				x = x + summands.get(i).calculate();
			} else {
				x = x - summands.get(i).calculate();
			}
		}
		return x;
	}

}